const sendSms = require('../utils/sms')
const { patterns } = require('../utils')
Parse.Cloud.define('getSmsCode', async (req, res) => {
  const { phone } = req.params
  if (!patterns.mobile.test(phone)) {
    return res.error('手机号码不正确')
  }
  try {
    const code = await sendSms(phone)
    const AuthCode = Parse.Object.extend('AuthCode')
    const authCode = new AuthCode({
      phone,
      code
    })
    const result = await authCode.save(null, { useMasterKey: true })
    res.success({
      id: result.id
    })
    // 清除之前的code
    const preCodes = await new Parse.Query('AuthCode').equalTo('phone', phone).notEqualTo('objectId', result.id).find()
    await Parse.Object.destroyAll(preCodes)
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})
